<template>
  <div class="searchBox">
    <a-select
      v-model:value="searchValue"
      show-search
      placeholder="请搜索: 首页 文章"
      style="width: 180px"
      :default-active-first-option="false"
      :filter-option="false"
      :not-found-content="null"
      size="small"
      @search="handleSearch"
      @select="handleSelect"
    >
      <a-select-option
        v-for="option in searchOptions"
        :key="option?.item?.path"
        :value="JSON.stringify(option?.item)"
      >
        {{ option?.item?.title?.join(' > ') }}
      </a-select-option>

      <template #suffixIcon>
        <Icon type="SearchOutlined" />
      </template>
    </a-select>
  </div>
</template>
<script setup>
import Icon from '@/components/Icon'
import Fuse from 'fuse.js'
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { filterRouters } from '@/utils/routes'
import { generateRoutes } from './FuseData.js'

const searchValue = ref(undefined)
// 生成模糊查询的数据源
const router = useRouter()
const searchPool = computed(() => {
  // 生成一个符合搜索格式的数组
  const filterRoutes = filterRouters(router.getRoutes())
  return generateRoutes(filterRoutes)
})

// 模糊搜索
const searchOptions = ref([])
//
const fuse = new Fuse(searchPool.value, {
  // 是否按优先级进行排序
  shouldSort: true,
  // 匹配长度超过这个值的才会被认为是匹配的
  minMatchCharLength: 1,
  keys: [
    {
      name: 'title',
      weight: 0.7
    },
    {
      name: 'path',
      weight: 0.3
    }
  ]
})
// 搜索中筛选数据
const handleSearch = (query) => {
  searchOptions.value = fuse.search(query)
}

// 选中搜索
const handleSelect = (value) => {
  const option = JSON.parse(value)
  router.push(option.path)
}
</script>
<style scoped lang="scss">
.searchBox {
  line-height: 100%;
  width: 200px;
}
</style>
